﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MailChimp4Umbraco.Businesslogic.ChimpAPI;
using System.Configuration;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.language;

namespace MailChimp4Umbraco.Userinterface.MailChimp4Umbraco
{
    public partial class MailChimpSubscibeSimple : System.Web.UI.UserControl
    {
        public string MailChimpListId { get; set; }
        public string OptionalRedirectToUrlAfterSuccess { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Set label texts
            NewsletterEmailLabel.Text = umbraco.library.GetDictionaryItem("MailChimp4Umbraco.subscribe.emailLabel");
            NewsletterSubmit.Text = umbraco.library.GetDictionaryItem("MailChimp4Umbraco.subscribe.submitButtonText");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            MailChimpCommunicator communicator = new MailChimpCommunicator(ConfigurationManager.AppSettings["MailChimp4Umbraco.APIKey"]);
            MailChimpResponse response = communicator.AddSubscriber(MailChimpListId, NewsletterEmailInput.Text, Request.UserHostAddress, string.Empty, string.Empty);
            
            if (response.IsSuccess)
            {
                if (!string.IsNullOrEmpty(OptionalRedirectToUrlAfterSuccess))
                {
                    Response.Redirect(OptionalRedirectToUrlAfterSuccess);
                } else
                {
                    // Get message from umbraco dictionary item
                    string message = umbraco.library.GetDictionaryItem("MailChimp4Umbraco.subscribe.subscriptionSuccess");
                    MessageLiteral.Text = string.Format("<div class=\"newsletter-sucess\">{0}</div>", message);
                }
            }
            else
            {
                // Get message from umbraco dictionary item
                string message = umbraco.library.GetDictionaryItem("MailChimp4Umbraco.error." + response.ErrorCode);
                string errorCode = string.Empty;
                if (string.IsNullOrEmpty(message))
                {
                    message = response.MailChimpErrorMessage;
                    errorCode = string.Format(" ({0})", response.ErrorCode);
                }
                MessageLiteral.Text = string.Format("<div class=\"newsletter-error\">{0}{1}</div>", message, errorCode);
                
            }
        }
    }
}